package com.mall.order.services;

import com.alibaba.fastjson.JSON;
import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 *  ciggar
 * create-date: 2019/7/30-上午10:05
 */
@Slf4j
@Component
@Service(cluster = "failfast")
public class OrderCoreServiceImpl implements OrderCoreService {

	@Autowired
	OrderMapper orderMapper;

	@Autowired
	OrderItemMapper orderItemMapper;

	@Autowired
	OrderShippingMapper orderShippingMapper;

	@Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

	@Autowired
	StockMapper stockMapper;

	//DefaultMQPushConsumer defaultMQPushConsumer;


	/**
	 * 创建订单的处理流程
	 *
	 * @param request
	 * @return
	 */
	@Override
	public CreateOrderResponse createOrder(CreateOrderRequest request) {
		CreateOrderResponse response = new CreateOrderResponse();
		try {
			//创建pipeline对象
			TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

			//启动pipeline
			invoker.start(); //启动流程（pipeline来处理）

			//获取处理结果
			AbsTransHandlerContext context = invoker.getContext();

			//把处理结果转换为response
			response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
		} catch (Exception e) {
			log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
			ExceptionProcessorUtils.wrapperHandlerException(response, e);
		}
		return response;
	}

	/**
	 * 取消订单
	 * @param cancelOrderRequest
	 * @return
	 */
	@Override
	public CancelOrderResponse cancelOrder(CancelOrderRequest cancelOrderRequest) {
		Order order = orderMapper.selectByPrimaryKey(cancelOrderRequest.getOrderId());

		//未支付的用户
		if (order.getStatus() == 0){
			orderMapper.updateByStatus(7,order.getOrderId());

			//查询orderid对应的orderItem表
			Example example = new Example(OrderItem.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("orderId",order.getOrderId());
			List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

			for (OrderItem orderItem : orderItems) {
				Stock stock = stockMapper.selectByPrimaryKey(orderItem.getItemId());
				Integer lockCount = stock.getLockCount();
				Long stockCount = stock.getStockCount();
				lockCount -=orderItem.getNum();
				stockCount +=orderItem.getNum();
				stockMapper.updateStockSetStockCAndnewNum(stockCount,lockCount.longValue(),orderItem.getItemId());
			}
			CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();
			cancelOrderResponse.setStatusStr("成功");
			cancelOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
			cancelOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
			return cancelOrderResponse;

		}//已经支付的用户
		else if (order.getStatus() == 1){
			orderMapper.updateByStatus(7,order.getOrderId());

			//查询orderid对应的orderItem表
			Example example = new Example(OrderItem.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("orderId",order.getOrderId());
			List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

			for (OrderItem orderItem : orderItems) {
				Stock stock = stockMapper.selectByPrimaryKey(orderItem.getItemId());
				Integer lockCount = stock.getLockCount();
				Long stockCount = stock.getStockCount();
				lockCount -=orderItem.getNum();
				stockCount +=orderItem.getNum();
				stockMapper.updateStockSetStockCAndnewNum(stockCount,lockCount.longValue(),orderItem.getItemId());
			}

			//返回支付费用，这个以后再弄

			//返回支付费用，这个以后再弄

			CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();
			cancelOrderResponse.setStatusStr("成功");
			cancelOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
			cancelOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
			return cancelOrderResponse;
		}else{
			CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();
			cancelOrderResponse.setStatusStr("该订单状态不能被取消");
			cancelOrderResponse.setCode(OrderRetCode.PIPELINE_RUN_EXCEPTION.getCode());
			cancelOrderResponse.setMsg(OrderRetCode.PIPELINE_RUN_EXCEPTION.getMessage());
			return cancelOrderResponse;
		}

	}

	/**
	 * 删除订单
	 * @param orderId
	 * @return
	 */
	@Override
	public DeleteOrderResponse deleteOrder(String orderId) {
		Order order = orderMapper.selectByPrimaryKey(orderId);

		//未支付的用户
		if (order.getStatus() == 0) {
			orderMapper.updateByStatus(8, order.getOrderId());

			//查询orderid对应的orderItem表
			Example example = new Example(OrderItem.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("orderId", order.getOrderId());
			List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

			for (OrderItem orderItem : orderItems) {
				Stock stock = stockMapper.selectByPrimaryKey(orderItem.getItemId());
				Integer lockCount = stock.getLockCount();
				Long stockCount = stock.getStockCount();
				lockCount -= orderItem.getNum();
				stockCount += orderItem.getNum();
				stockMapper.updateStockSetStockCAndnewNum(stockCount, lockCount.longValue(), orderItem.getItemId());
			}
			DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();
			deleteOrderResponse.setStatusStr("成功");
			deleteOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
			deleteOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
			return deleteOrderResponse;

		}//已经支付的用户
		else if (order.getStatus() == 1) {
			orderMapper.updateByStatus(8, order.getOrderId());

			//查询orderid对应的orderItem表
			Example example = new Example(OrderItem.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("orderId", order.getOrderId());
			List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

			for (OrderItem orderItem : orderItems) {
				Stock stock = stockMapper.selectByPrimaryKey(orderItem.getItemId());
				Integer lockCount = stock.getLockCount();
				Long stockCount = stock.getStockCount();
				lockCount -= orderItem.getNum();
				stockCount += orderItem.getNum();
				stockMapper.updateStockSetStockCAndnewNum(stockCount, lockCount.longValue(), orderItem.getItemId());
			}

			//返回支付费用，这个以后再弄

			//返回支付费用，这个以后再弄

			DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();
			deleteOrderResponse.setStatusStr("成功");
			deleteOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
			deleteOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
			return deleteOrderResponse;
		}//状态4是已经交易成功，那么删除已经交易成功的订单，就只需要修改订单中status就可以了
		else if (order.getStatus() == 4) {
			orderMapper.updateByStatus(8, order.getOrderId());

			DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();
			deleteOrderResponse.setStatusStr("成功");
			deleteOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
			deleteOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
			return deleteOrderResponse;
		}
		return null;
	}


	//如果时间长没有支付订单，则取消订单
	//因为本类是spring组件，开所以起应用就加载
//	@PostConstruct
//	public void init(){
//
//		defaultMQPushConsumer = new DefaultMQPushConsumer("consumer_group");
//
//		defaultMQPushConsumer.setNamesrvAddr("localhost:9876");
//
//		try {
//			defaultMQPushConsumer.subscribe("order","*");
//		} catch (MQClientException e) {
//			e.printStackTrace();
//		}
//
//		defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
//			@Override
//			public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
//				MessageExt messageExt = msgs.get(0);
//				byte[] body = messageExt.getBody();
//
//				String bodyStr = new String(body);
//
//				Map<String,Object> map = JSON.parseObject(bodyStr, Map.class);
//
//				Integer userId = (Integer) map.get("userId");
//				String orderId = (String) map.get("order");
//
//				// 处理相应的业务逻辑
//				Order order = orderMapper.selectByPrimaryKey(orderId);
//				if (order.getStatus()==0){
//
//					//将订单取消
//					orderMapper.updateByStatus(7,orderId);
//
//					//查询orderid对应的orderItem表
//					Example example = new Example(OrderItem.class);
//					Example.Criteria criteria = example.createCriteria();
//					criteria.andEqualTo("orderId", order.getOrderId());
//					List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
//
//					//修改库存
//					for (OrderItem orderItem : orderItems) {
//						Stock stock = stockMapper.selectByPrimaryKey(orderItem.getItemId());
//						Long stockCount = stock.getStockCount();
//						stockCount += orderItem.getNum();
//						Integer lockCount = stock.getLockCount();
//						lockCount -=orderItem.getNum();
//						stockMapper.updateStockSetStockCAndnewNum(stockCount,lockCount.longValue(),orderItem.getItemId());
//					}
//				}
//				return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
//			}
//		});
//		try {
//			defaultMQPushConsumer.start();
//		} catch (MQClientException e) {
//			e.printStackTrace();
//		}
//	}

}
